from fastapi import APIRouter, Depends, HTTPException, status, Query
from sqlalchemy.orm import Session
from typing import List, Optional
from uuid import UUID
from datetime import datetime

from app.database.base import get_db
from app.schemas.maintenance_record import (
    MaintenanceRecordCreate, 
    MaintenanceRecordUpdate, 
    MaintenanceRecordResponse,
    MaintenanceRecordComplete,
    MaintenanceRecordApprove,
    MaintenanceRecordFilter,
    MaintenanceStatsResponse
)
from app.models.maintenance_record import MaintenanceType, MaintenanceStatus
from app.services.maintenance_record import MaintenanceRecordService
from app.core.auth import get_current_user
from app.models.user import User

router = APIRouter(prefix="/maintenance-records", tags=["maintenance-records"])
maintenance_service = MaintenanceRecordService()

@router.post("/save", response_model=MaintenanceRecordResponse, status_code=status.HTTP_201_CREATED)
async def create_maintenance_record(
    record_data: MaintenanceRecordCreate,
    db: Session = Depends(get_db),
    current_user: User = Depends(get_current_user)
):
    """创建维护记录"""
    try:
        return maintenance_service.create(db, obj_in=record_data, created_by=current_user.id)  # type: ignore
    except Exception as e:
        raise HTTPException(status_code=400, detail=str(e))

@router.get("/list", response_model=List[MaintenanceRecordResponse])
async def get_maintenance_records(
    skip: int = Query(0, ge=0),
    limit: int = Query(100, ge=1, le=1000),
    device_id: Optional[UUID] = None,
    maintenance_type: Optional[MaintenanceType] = None,
    status: Optional[MaintenanceStatus] = None,
    priority: Optional[str] = None,
    assigned_to: Optional[UUID] = None,
    performed_by: Optional[UUID] = None,
    start_date: Optional[datetime] = None,
    end_date: Optional[datetime] = None,
    is_overdue: Optional[bool] = None,
    db: Session = Depends(get_db),
    current_user: User = Depends(get_current_user)
):
    """获取维护记录列表"""
    filters = MaintenanceRecordFilter(
        device_id=device_id,
        maintenance_type=maintenance_type,
        status=status,
        priority=priority,
        assigned_to=assigned_to,
        performed_by=performed_by,
        start_date=start_date,
        end_date=end_date,
        is_overdue=is_overdue
    )
    
    return maintenance_service.get_multi(db, skip=skip, limit=limit, filters=filters)

@router.get("/overdue", response_model=List[MaintenanceRecordResponse])
async def get_overdue_records(
    db: Session = Depends(get_db),
    current_user: User = Depends(get_current_user)
):
    """获取逾期的维护记录"""
    return maintenance_service.get_overdue_records(db)

@router.get("/stats", response_model=MaintenanceStatsResponse)
async def get_maintenance_stats(
    device_id: Optional[UUID] = None,
    start_date: Optional[datetime] = None,
    end_date: Optional[datetime] = None,
    db: Session = Depends(get_db),
    current_user: User = Depends(get_current_user)
):
    """获取维护统计信息"""
    return maintenance_service.get_stats(
        db, 
        device_id=device_id, 
        start_date=start_date, 
        end_date=end_date
    )

@router.get("/{record_id}", response_model=MaintenanceRecordResponse)
async def get_maintenance_record(
    record_id: UUID,
    db: Session = Depends(get_db),
    current_user: User = Depends(get_current_user)
):
    """获取维护记录详情"""
    record = maintenance_service.get(db, record_id)
    if not record:
        raise HTTPException(status_code=404, detail="维护记录不存在")
    return record

@router.put("/{record_id}", response_model=MaintenanceRecordResponse)
async def update_maintenance_record(
    record_id: UUID,
    record_data: MaintenanceRecordUpdate,
    db: Session = Depends(get_db),
    current_user: User = Depends(get_current_user)
):
    """更新维护记录"""
    record = maintenance_service.get(db, record_id)
    if not record:
        raise HTTPException(status_code=404, detail="维护记录不存在")
    
    try:
        return maintenance_service.update(db, db_obj=record, obj_in=record_data)
    except Exception as e:
        raise HTTPException(status_code=400, detail=str(e))

@router.post("/{record_id}/start", response_model=MaintenanceRecordResponse)
async def start_maintenance(
    record_id: UUID,
    db: Session = Depends(get_db),
    current_user: User = Depends(get_current_user)
):
    """开始维护工作"""
    try:
        record = maintenance_service.start_maintenance(
            db, 
            record_id=record_id, 
            performed_by=current_user.id  # type: ignore
        )
        if not record:
            raise HTTPException(status_code=404, detail="维护记录不存在")
        return record
    except ValueError as e:
        raise HTTPException(status_code=400, detail=str(e))
    except Exception as e:
        raise HTTPException(status_code=500, detail=str(e))

@router.post("/{record_id}/complete", response_model=MaintenanceRecordResponse)
async def complete_maintenance(
    record_id: UUID,
    completion_data: MaintenanceRecordComplete,
    db: Session = Depends(get_db),
    current_user: User = Depends(get_current_user)
):
    """完成维护工作"""
    try:
        record = maintenance_service.complete_maintenance(
            db, 
            record_id=record_id, 
            completion_data=completion_data
        )
        if not record:
            raise HTTPException(status_code=404, detail="维护记录不存在")
        return record
    except ValueError as e:
        raise HTTPException(status_code=400, detail=str(e))
    except Exception as e:
        raise HTTPException(status_code=500, detail=str(e))

@router.post("/{record_id}/approve", response_model=MaintenanceRecordResponse)
async def approve_maintenance(
    record_id: UUID,
    approval_data: MaintenanceRecordApprove,
    db: Session = Depends(get_db),
    current_user: User = Depends(get_current_user)
):
    """审核维护记录"""
    try:
        record = maintenance_service.approve_maintenance(
            db, 
            record_id=record_id, 
            approved_by=current_user.id,  # type: ignore
            approved=approval_data.approved
        )
        if not record:
            raise HTTPException(status_code=404, detail="维护记录不存在")
        return record
    except ValueError as e:
        raise HTTPException(status_code=400, detail=str(e))
    except Exception as e:
        raise HTTPException(status_code=500, detail=str(e))

@router.post("/{record_id}/cancel", response_model=MaintenanceRecordResponse)
async def cancel_maintenance(
    record_id: UUID,
    db: Session = Depends(get_db),
    current_user: User = Depends(get_current_user)
):
    """取消维护记录"""
    try:
        record = maintenance_service.cancel_maintenance(db, record_id=record_id)
        if not record:
            raise HTTPException(status_code=404, detail="维护记录不存在")
        return record
    except ValueError as e:
        raise HTTPException(status_code=400, detail=str(e))
    except Exception as e:
        raise HTTPException(status_code=500, detail=str(e))

@router.delete("/{record_id}")
async def delete_maintenance_record(
    record_id: UUID,
    db: Session = Depends(get_db),
    current_user: User = Depends(get_current_user)
):
    """删除维护记录"""
    record = maintenance_service.remove(db, id=record_id)
    if not record:
        raise HTTPException(status_code=404, detail="维护记录不存在")
    
    return {"message": "维护记录删除成功"}

@router.post("/update-overdue-status")
async def update_overdue_status(
    db: Session = Depends(get_db),
    current_user: User = Depends(get_current_user)
):
    """更新逾期记录状态（管理员功能）"""
    if current_user.role not in ["admin", "manager"]:
        raise HTTPException(status_code=403, detail="权限不足")
    
    count = maintenance_service.update_overdue_status(db)
    return {"message": f"更新了 {count} 条逾期记录"}